package com.azt.back.action.echarts;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.azt.api.dto.EcharsProjectArea;
import com.azt.api.dto.UserForEcharts;
import com.azt.api.service.EnqEnquiryService;
import com.azt.api.service.OrderService;
import com.azt.api.service.UserService;
import com.azt.back.action.BaseAction;
import com.azt.model.AjaxJson;
import com.github.abel533.echarts.*;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.data.Data;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.itemstyle.Emphasis;
import com.github.abel533.echarts.style.itemstyle.Normal;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.date.DateUtil;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by 张栋 on 2016/12/1513:1  0
 */
@Controller
@RequestMapping("/echarts")
public class EchartsJsonAction extends BaseAction {

    @Autowired
    private UserService userService;

    @Autowired
    private EnqEnquiryService es;

    @Autowired
    private OrderService orderService;

    /**
     * 新增认证用户
     */
    @RequestMapping("/user/added.do")
    @ResponseBody
    public AjaxJson  added(){

        //新增用户
        List<UserForEcharts> maps = userService.echartsAdded();
        //新增认证过的用户
        List<UserForEcharts> auth = userService.echartsAddedAuth();

        List<String> datasa = new ArrayList<>();
        List<String> datasb = new ArrayList<>();
        List<String> datasc = new ArrayList<>();
        List<String> datasd = new ArrayList<>();
        List<String> datase = new ArrayList<>();
        List<String> times = new ArrayList<>();
        for (UserForEcharts d : maps) {
            datasa.add(d.getCounta()+"");
            datasb.add(d.getCountb()+"");
            datasc.add(d.getCountc()+"");
            datasd.add(d.getCountd()+"");
            datase.add(d.getCounte()+"");
            times.add(d.getFulldate());
        }
        //创建Option
        GsonOption option = new GsonOption();
        option.title("新增认证用户").tooltip(Trigger.axis).legend("月");
        CategoryAxis valueAxis = new CategoryAxis();
        valueAxis.data(times.toArray());
        valueAxis.name("年-月");
        option.xAxis(valueAxis);
        ValueAxis y = new ValueAxis();
        y.name("数量");
        option.yAxis(y);

        Bar bara = new Bar();
        bara.name("注册");
        bara.data(datasa.toArray());

        Bar barb = new Bar();
        barb.name("认证");
        barb.data(datasb.toArray());
        //barb.stack("sum");

        Bar barc = new Bar();
        barc.name("采购商");
        barc.data(datasc.toArray());
        barc.stack("sum");

        Bar bard = new Bar();
        bard.name("供应商");
        bard.data(datasd.toArray());
        bard.stack("sum");

        Bar bare = new Bar();
        bare.name("双身份");
        bare.data(datase.toArray());
        bare.stack("sum");


        Normal normal = new Normal();
        ItemStyle itemStyle = new ItemStyle();
        normal.color("rgba(193,35,43,1)");
        itemStyle.normal(normal);


        ItemStyle itemStyleb = new ItemStyle();
        Normal normalb = new Normal();
        normalb.color("rgba(252,100,16,1)");
        itemStyleb.normal(normalb);

        ItemStyle itemStylec = new ItemStyle();
        Normal normalc = new Normal();
        normalc.color("rgba(252,206,16,1)");
        itemStylec.normal(normalc);

        ItemStyle itemStyled = new ItemStyle();
        Normal normald = new Normal();
        normald.color("rgba(181,195,52,1)");
        itemStyled.normal(normald);




        bara.itemStyle(itemStyle);
        barb.itemStyle(itemStyleb);
        barc.itemStyle(itemStylec);
        bard.itemStyle(itemStyled);
        bare.itemStyle(itemStyle);
        option.series(barb,bard,barc,bare);



        //tool
        AjaxJson j = new AjaxJson();
        Map<String,Object>  other = new HashedMap();
        JSONObject obj = (JSONObject) JSON.toJSON(bara);
        System.out.println(obj);
        other.put("totals",obj);
        j.setAttributes(other);
        j.setObj(JSONObject.parseObject(option.toString()));
        return j ;
    }

    //项目所在地统计
    @RequestMapping("/project/grid.do")
    @ResponseBody
    public AjaxJson projectArea(){
        AjaxJson j = new AjaxJson();
        List<EcharsProjectArea> echarsProjectAreas = es.projectArea();
        JSONArray arrall = new JSONArray();
        Integer bigcount =0;
        for (int i = 0; i < echarsProjectAreas.size(); i++) {
            EcharsProjectArea epa = echarsProjectAreas.get(i);
            JSONObject obj = new JSONObject();
            obj.put("name",epa.getName());
            JSONArray arrs = new JSONArray();
            arrs.add(epa.getX());
            arrs.add(epa.getY());
            arrs.add(epa.getCount());
            if(epa.getCount()>bigcount){
                bigcount = epa.getCount();
            }
            obj.put("value",arrs);
            arrall.add(obj);
        }

        j.setMsg(bigcount+"");
        j.setObj(arrall);
        return j;
    }

    @ResponseBody
    @RequestMapping("/statistics.do")
    public AjaxJson statistics() {
        Integer type = getParaToInt("type", 1);
        Date sdate = getParaToDate("sdate", "yyyy-MM");
        Date edate = getParaToDate("edate", "yyyy-MM");
        Map param = new HashMap();
        param.put("sdate", sdate);
        if(edate != null) {
            param.put("edate", DateUtil.beginOfMonth(DateUtil.offsetMonth(edate, 1)));
        }
        Option option = null;
        if(type == 1) {
            // 统计注册用户
            List<Map> result = userService.statisticsUser(param);
            option = new GsonOption();
            option.title(new Title().text("注册用户"));
            option.color("#749f83");
            option.tooltip(new Tooltip().trigger(Trigger.axis));
            option.grid(new Grid().left("3%").right("4%").bottom("3%").containLabel(true));
            CategoryAxis categoryAxis = new CategoryAxis().name("月份");
            Bar bar = new Bar().name("注册用户数量");
            for(Map data : result) {
                String date = Convert.toStr(data.get("date"));
                Integer num = Convert.toInt(data.get("num"));
                categoryAxis.data(date);
                bar.data(num);
            }
            option.xAxis(categoryAxis);
            option.yAxis(new ValueAxis().name("数量"));
            option.series(bar);
        } else if(type == 2) {
            // 统计交易量
            List<Map> result = orderService.statisticeOrder(param);
            option = new GsonOption();
            option.title(new Title().text("交易量"));
            option.color("#749f83");
            option.tooltip(new Tooltip().trigger(Trigger.axis));
            option.grid(new Grid().left("3%").right("4%").bottom("3%").containLabel(true));
            CategoryAxis categoryAxis = new CategoryAxis().name("月份");
            Bar bar = new Bar().name("交易量");
            for(Map data : result) {
                String date = Convert.toStr(data.get("date"));
                Double total = Convert.toDouble(data.get("total"));
                categoryAxis.data(date);
                bar.data(total);
            }
            option.xAxis(categoryAxis);
            option.yAxis(new ValueAxis().name("金额（元）"));
            option.series(bar);
        }
        if(option != null) {
            return AjaxJson.success().setObj(option.toString());
        } else {
            return AjaxJson.error();
        }
    }

    @ResponseBody
    @RequestMapping("/statisticsDetail.do")
    public AjaxJson statisticsDetail() {
        Integer type = getParaToInt("type", 1);
        Date date = getParaToDate("date", "yyyy-MM");

        Option option = null;
        if(date != null) {
            Date edate = DateUtil.offsetMonth(date, 1);
            Map param = new HashMap();
            param.put("sdate", date);
            param.put("edate", edate);

            if(type == 1) {
                //注册用户明细
                List<Map> result = userService.statisticsUserDetail(param);
                option = new GsonOption();
                option.title(new Title().text(getParaTrim("date") + "注册用户明细").x("center"));
                option.tooltip(new Tooltip().trigger(Trigger.item).formatter("{a} <br/>{b} : {c} ({d}%)"));
                option.legend(new Legend().orient(Orient.vertical).left("left").data("采购商", "供应商", "双重身份", "未关联公司"));
                Pie pie = new Pie().name("明细").radius("55%").center("50%", "60%");
                pie.itemStyle(new ItemStyle().emphasis(new Emphasis().shadowBlur(10).shadowOffsetX(0).shadowColor("rgba(0, 0, 0, 0.5)")));
                for(Map data : result) {
                    Integer noCompanyCount = Convert.toInt(data.get("noCompanyCount"), 0);      //未关联公司
                    Integer purchaserCount = Convert.toInt(data.get("purchaserCount"), 0);      //采购商
                    Integer providerCount = Convert.toInt(data.get("providerCount"), 0);      //供应商
                    Integer bothCount = Convert.toInt(data.get("bothCount"), 0);      //双重身份
                    pie.data(new Data("采购商", purchaserCount), new Data("供应商", providerCount), new Data("双重身份", bothCount), new Data("未关联公司", noCompanyCount));
                }
                option.series(pie);
            } else if(type == 2) {
                //交易量
                List<Map> result = orderService.statisticeOrderDetail(param);
                option = new GsonOption();
                option.title(new Title().text(getParaTrim("date") + "交易量明细").x("center"));
                option.tooltip(new Tooltip().trigger(Trigger.item).formatter("{a} <br/>{b} : {c} ({d}%)"));
                option.legend(new Legend().orient(Orient.vertical).left("left").data("询价订单", "商城订单"));
                Pie pie = new Pie().name("明细").radius("55%").center("50%", "60%");
                pie.itemStyle(new ItemStyle().emphasis(new Emphasis().shadowBlur(10).shadowOffsetX(0).shadowColor("rgba(0, 0, 0, 0.5)")));
                for(Map data : result) {
                    Double productTotla = Convert.toDouble(data.get("productTotla"), 0d);      //商城订单金额
                    Double enquiryTotal = Convert.toDouble(data.get("enquiryTotal"), 0d);      //询价订单金额
                    pie.data(new Data("商城订单", productTotla), new Data("询价订单", enquiryTotal));
                }
                option.series(pie);
            }
        }

        if(option != null) {
            return AjaxJson.success().setObj(option.toString());
        } else {
            return AjaxJson.error();
        }
    }

}
